﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.ComponentModel;
using System.Threading;

namespace wpfTCPListener
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        Int32 m_port = 13000;
        TcpListener m_server;
        private BackgroundWorker m_bwListener;
        private List<BackgroundWorker> m_listBW = new List<BackgroundWorker>();

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            IPAddress localAddr = IPAddress.Parse("172.17.86.46");
            m_server = new TcpListener(localAddr, m_port);
            m_server.Start();

            m_bwListener = new BackgroundWorker();
            m_bwListener.WorkerSupportsCancellation = true;
            m_bwListener.DoWork += new DoWorkEventHandler(m_bwListener_DoWork);
            m_bwListener.RunWorkerAsync();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            m_bwListener.CancelAsync();

            if (m_server != null)
            {
                m_server.Stop();
            }
        }

        #region bwListener

        void m_bwListener_DoWork(object sender, DoWorkEventArgs e)
        {
            int i = 0;

            while (!e.Cancel)
            {
                if (!m_server.Pending())
                {
                    Thread.Sleep(1000); // choose a number (in milliseconds) that makes sense
                    continue; // skip to next iteration of loop
                }
                else
                {
                    TcpClient client = m_server.AcceptTcpClient();

                    BWSArgs bws = new BWSArgs
                    {
                        Client = client,
                        FileName = string.Format("Files\\{0}.txt", i),
                        FileSize = 0
                    };

                    BackgroundWorker bw = new BackgroundWorker();
                    bw.WorkerSupportsCancellation = true;
                    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                    m_listBW.Add(bw);
                    bw.RunWorkerAsync(bws);
                    ++i;
                }
            }
        }

        #endregion

        #region bwReciver

        private int m_sendSize = 172032;

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            BWSArgs bws = e.Result as BWSArgs;
            bws.Client.Close();
            m_listBW.Remove(bw);
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BWSArgs bws = e.Argument as BWSArgs;

            NetworkStream stream = bws.Client.GetStream();
            Byte[] bytes = new Byte[m_sendSize];

            int i;

            BinaryWriter bWrite = new BinaryWriter(File.Open(bws.FileName, FileMode.OpenOrCreate));
            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                bWrite.Write(bytes, 0, i);
            }
            bWrite.Close();

            e.Result = bws;
        }

        #endregion
    }

    public class BWSArgs
    {
        public TcpClient Client { get; set; }
        public string FileName { get; set; }
        public long FileSize { get; set; }
    }
}
